LeetCode JS Easy 2704. To Be Or Not To Be


Posted by Lucy on 2023-06-10

這是30 Days of JavaScript中的題型
Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.

toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal".
notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal".
最常見寫法應該就兩個function

var expect = function(val) {
    const toBe=(eqalVal)=>{if(val===eqalVal)return true
                throw new Error("Not Equal")
    }    
    const notToBe=(eqalVal)=>{if(val!==eqalVal)return true
                throw new Error("Equal")
    }
      return {
          toBe:toBe,
          notToBe:notToBe,
      }
};

不過不知道為什麼我就很想寫共用function,下面這段是第一次寫的

var expect = function(val) {
    const fn=(eqalVal,isToBe)=>{
            const isEqal=val===eqalVal
            if(isToBe){
                if(isEqal)return true
                throw new Error("Not Equal")
            }else{
                if(isEqal)throw new Error("Equal")
                return true
            }
        }
      return {
          toBe:(eqalVal)=>fn(eqalVal,true),
          notToBe:(eqalVal)=>fn(eqalVal,false),
      }
};

#leetcode Js







Related Posts

[Note] JS: Function 觀念

[Note] JS: Function 觀念

JavaScript 變數型態判斷及賦值

JavaScript 變數型態判斷及賦值

[Math] 如何於CoderBridge撰寫數學公式

[Math] 如何於CoderBridge撰寫數學公式


Comments